package org.linlinjava.litemall.admin.webSocket.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint("/adminWs")
public class AdminWebSocketService {

    private Session session;

    private static CopyOnWriteArraySet<AdminWebSocketService> webSockets = new CopyOnWriteArraySet<>();
    private static Map<String, Session> sessionPool = new HashMap();
    /*
     * @description: 有新的连接加入
     * @author: wangxihao
     * @date:2022/8/30 15:16
     * @param: session
     **/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(session.getId(), session);
        // 新的连接加入 通知客户端
        sendMessageToAll(webSockets.size() + "");
        System.out.println("【websocket消息】有新的连接，总数为:" + webSockets.size());
    }
    /*
     * @description: websocket消息连接断开
     * @author: wangxihao
     * @date:2022/8/30 15:16
     **/
    @OnClose
    public void onClose() {
        webSockets.remove(this);
        // 断开连接 通知客户端
        sendMessageToAll(webSockets.size() + "");
        System.out.println("【websocket消息】连接断开，总数为:" + webSockets.size());
    }
    /*
     * @description: websocket消息收到客户端消息
     * @author: wangxihao
     * @date:2022/8/30 15:16
     * @param: message
     **/
    @OnMessage
    public void onMessage(String message) {
        System.out.println("websocket消息收到客户端消息:" + message);
        JSONObject jsonObject = JSON.parseObject(message);
        //JSON.toJavaObject(jsonObject,);
        String sid = jsonObject.getString("sid");

        for (AdminWebSocketService webSocket : webSockets) {
            System.out.println("【websocket】通知所有的客户端:" + message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 通知所有的客户端
     *
     * @param message
     */
    public void sendMessageToAll(String message) {
        for (AdminWebSocketService webSocket : webSockets) {
            System.out.println("【websocket】通知所有的客户端:" + message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
